package com.kuang.login;

import com.kuang.login.model.User;
import com.kuang.login.model.UserMysqlModel;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * Created by 郭浩 on 2020/9/25 16:38
 */
@WebServlet("/user")
public class userServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String op = request.getParameter("op");
        if (op.equals("register")){
            register(request,response);
        }

    }

    private void register(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map<String, String[]> map = request.getParameterMap();
        //使用工具类将对应得数据封装成对象
        User user = new User();
        try {
            BeanUtils.populate(user,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        //检查注册是否符合要求
        if (user.isEmpty()){
            try {
                response.getWriter().println("用户信息不存在");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        int register = UserMysqlModel.register(user);
        if (register == 404){
            response.getWriter().println("当前用户名已经被注册，请更换");
        }else if (register == 500){
            response.getWriter().println("当前服务繁忙，稍后重试");
        }

        response.getWriter().println("注册成功，跳转至登录页面");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
